﻿using System;
using System.Collections.Generic;

using System.Text;

namespace Efficient.Domain
{
    [Serializable]
    public class GenericListItem<T>
    {
        private List<T> itemList = new List<T>();

        public event EventHandler<GenericEventArgs<T>> ItemAdd;

        public void AddItem(T item)
        {
            if (!itemList.Contains(item))
            {
                if (ItemAdd != null)
                { 
                    ItemAdd(this, new GenericEventArgs<T>(item));
                }
                itemList.Add(item);
            }
        }

        public void AddItems(IEnumerable<T> items)
        {
            foreach (T item in items)
            {
                AddItem(item);
            }
        }

        public void SaveOrUpdate(T item)
        {
            if (itemList.Contains(item))
            {
                itemList.Remove(item);
            }
            itemList.Add(item);
        }

        public void RemoveItems(Predicate<T> condition)
        {
            for (int i = itemList.Count - 1; i >= 0; i--)
            {
                T item = itemList[i];
                if (condition(item))
                {
                    itemList.RemoveAt(i);
                }
            }
        }

        public void RemoveItem(T item)
        {
            if (itemList.Contains(item))
            {
                itemList.Remove(item);
            }
        }

        public bool ExistItem(T item)
        {
            return itemList.Contains(item);
        }

        public void RemoveAll()
        {
            itemList.Clear();
        }

        public IList<T> GetItems()
        {
            return this.itemList.AsReadOnly();
        }

        public T Find(Predicate<T> condition)
        {
            return this.itemList.Find(condition);
        }

        public IList<T> FindAll(Predicate<T> condition)
        {
            return this.itemList.FindAll(condition);
        }

        public IList<T> Sort(IComparer<T> comparer)
        {
            this.itemList.Sort(comparer);
            return this.itemList.AsReadOnly();
        }

        public IList<T> Sort()
        {
            this.itemList.Sort();
            return this.itemList.AsReadOnly();
        }
    }
}
